﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RangeDevice : DeviceBase
{
    const string STATE_RUNNING = "running";

    [SerializeField]
    private float Range = 100;
    public float Min { get; private set; }
    public float Max { get; private set; }

    public float NormalValue { get; private set; } = 0;
    public float Value 
    { 
        get
        {
            return NormalValue * Range + Min;
        }
    }

    private int _playDir = 0;

    protected override void Start()
    {
        base.Start();
        Clear();
    }

    void Update()
    {
        if (_playDir == 0)
            return;

        if (_playDir == 1 && NormalValue < 1)
        {
            NormalValue += 0.3f * Time.deltaTime;
            if (NormalValue >= 1)
            {
                NormalValue = 1;
                _playDir = 0;
            }
        }
        else if (_playDir == -1 && NormalValue > 0)
        {
            NormalValue -= 0.3f * Time.deltaTime;
            if (NormalValue <= 0)
            {
                NormalValue = 0;
                _playDir = 0;
            }
        }
    }

    /// <summary>
    /// 调整Min和Max的值，使得当前Value为0
    /// </summary>S
    public override void Clear()
    {
        Min = -NormalValue * Range;
        Max = Min + Range;
    }

    public override void ClearToMin()
    {
        NormalValue = 0;
        Clear();
    }

    public override void ClearToMax()
    {
        NormalValue = 1;
        Clear();
    }

    public override string GetDeviceStatusCore()
    {
        return $"{STATE_RUNNING},{Value}";
    }

    public void SetRange(float value) 
    {
        Range = value;
        Clear();
    }

    public void PlayBack() { _playDir = -1; }
    public void PlayForward() { _playDir = 1; }
    public void Stop() { _playDir = 0; }

    public void SetNormalValue(float normalValue)
    {
        NormalValue = Mathf.Clamp01(normalValue);
    }
}
